/**
 * mission {
 *     ttl :  time to live,
 *     func: exec function,
 *     data :{
 *          creepName,creepMmeory,……
 *     } ,
 * }
 */

let TTL = 5000 // 大概4小时

// return true if success else false （py写多了)
global.missionFunc = { //被crossShard引用 ，相当于交叉依赖了
    test:function (data) {
        log(data)
        return true;
    },
    setCreepMemory:function (data) {
         let creep = Game.creeps[data.name]
        if(creep){
            creep.memory = data.memory;
            return true;
        }
        return false;
    },
    /**
     * @param data : {spawnRoom:String,targetRoomName:String,body:[MOVE],role:String,tasks:[]}
     */
    spawnCreepCressShard:function (data) {
        let room = Game.rooms[data.spawnRoom]
        // log(data)
        if(!room)return true;
        // log(room.name)
        return StationHive.trySpawn(room, data.targetRoomName, data.body, data.role, data.tasks);
    },
    /**
     * @param data : {fromRoomName:String,toRoomName:String,resType:ResourceConstant,amount:number}
     */
    sendRes:function (data){
        let from = Game.rooms[data.fromRoomName]
        if(from&&from.my){
            let terminal = from.room.terminal;
            if(terminal){
                terminal._need_hold = terminal._need_hold||{}
                terminal._need_hold[data.resType] = (terminal._need_hold[data.resType]||0) + data.amount
            }
            if(terminal&&from.terminal.cooldown==0){
                let cnt = Math.min(from.terminal.store[resType],data.amount);
                if(cnt&&(cnt==data.amount||cnt>=3000)){
                    let code = from.terminal.send(data.resType,data.amount,data.toRoomName)
                    if(code==OK){
                        data.amount -= cnt;
                        if(!data.amount)return true;
                    }
                }
            }
        }
        return false;
    }
}


global.missionCallBack = { //被crossShard引用 ，相当于交叉依赖了
    setFlagMemory:function (data) { //todo 测试失败
        let flag = Game.flags[data.flagName]
        if(flag){
            for(let t in data.flagMemory){
                flag.memory[t] = data.flagMemory;
            }
            return true;
        }
        return false;
    },
}

let pro={
    getTaskId:function (){
        Game._mission_cnt = ( Game._mission_cnt || 0 ) + 1;
        return Game.time +"_"+ Game._mission_cnt;
    },
    init:function() {
        let missions  = (Memory.missions = Memory.missions || {});

        Object.entries(missions).forEach(l=>{
            let id = l[0];
            let e = l[1];
            e.ttl = e.ttl===undefined ? TTL:e.ttl-1;
            if(!e.ttl)delete missions[id];
            else if(missionFunc[e.func](e.data))delete missions[id];
        })
    },

};


global.ManagerMissions = pro;